package com.example.blade.cavasapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by blade on 2017/9/14.
 */

public class CustomCanvas extends View {

    private Context mContext;
    private int mViewWidth, mViewHeight;

    private Paint mPaint;
    private Bitmap mBitmap;
    private Canvas mCanvas;

    private Path mPath;

    private List<Path> mSavePathList = new ArrayList<>();
    private List<Path> mDeletePathList = new ArrayList<>();

    public CustomCanvas(Context context) {
        super(context);

        mContext = context;

        initPaint();
    }

    public CustomCanvas(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        mContext = context;

        initPaint();
    }

    public CustomCanvas(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(8);
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setAntiAlias(true);
    }

    private void initCanvas(int width, int height) {
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mBitmap.eraseColor(Color.argb(0, 0, 0, 0));
        mCanvas = new Canvas(mBitmap);  //所有mCanvas画的东西都被保存在了mBitmap中
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mViewWidth = MeasureSpec.getSize(widthMeasureSpec);
        mViewHeight = MeasureSpec.getSize(heightMeasureSpec);

        initCanvas(mViewWidth, mViewHeight);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                mPath = new Path();
                mPath.moveTo(x, y);

                break;

            case MotionEvent.ACTION_MOVE:

                mPath.lineTo(x, y);
                mCanvas.drawPath(mPath, mPaint);
                invalidate();

                break;

            case MotionEvent.ACTION_UP:

                mSavePathList.add(mPath);
                mPath = null;// 重新置空

                break;
        }


        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(mBitmap, 0, 0, null);

    }

    public void backward() {

        if (mSavePathList.size() > 0) {
            Path deletedPath = mSavePathList.get(mSavePathList.size() - 1);
            mDeletePathList.add(deletedPath);
            mSavePathList.remove(mSavePathList.size() - 1);

            redrawOnBitmap();
        }

    }

    private void redrawOnBitmap() {

        initCanvas(mViewWidth,mViewHeight);

//        Iterator<DrawPath> iter = savePath.iterator();
//        while (iter.hasNext()) {
//            DrawPath drawPath = iter.next();
//            mCanvas.drawPath(drawPath.path, drawPath.paint);
//        }

        for (Path p : mSavePathList) {
            mCanvas.drawPath(p, mPaint);
        }
        invalidate();
    }

    public void forward() {

        if (mDeletePathList.size() > 0) {
            //将删除的路径列表中的最后一个，也就是最顶端路径取出（栈）,并加入路径保存列表中
            Path path = mDeletePathList.get(mDeletePathList.size() - 1);
            mSavePathList.add(path);
            //将取出的路径重绘在画布上
            mCanvas.drawPath(path, mPaint);
            //将该路径从删除的路径列表中去除
            mDeletePathList.remove(mDeletePathList.size() - 1);
            invalidate();
        }

    }

    public void clearCanvas() {

        if (mSavePathList.size() > 0) {
            mSavePathList.clear();
            redrawOnBitmap();
        }

    }

    public void erase() {
    }

    public String saveToLocal() {

        //获得系统当前时间，并以该时间作为文件名
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String name = formatter.format(curDate) + "-canvas.png";
        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath(), name);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        //发送Sd卡的就绪广播,要不然在手机图库中不存在
//        Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
//        intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
//        context.sendBroadcast(intent);
        Log.e("TAG", "图片已保存");

        return file.getPath();

    }
}
